﻿using AutoMapper;
using Blog.Application.Contract.Blogs;
using Blog.Application.Contract.Blogs.Dto;
using Blog.EntityFrameworkCore;
using Blog.Module;
using Infrastructure;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Blog.Application.Blogs;

public class BlogTypeService : IBlogTypeService
{
    private readonly BlogDbContext _blogDbContext;
    private readonly IMapper _mapper;

    public BlogTypeService(BlogDbContext blogDbContext, IMapper mapper)
    {
        _blogDbContext = blogDbContext;
        _mapper = mapper;
    }

    /// <summary>
    /// 创建博客类型
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    /// <exception cref="BusinessExecptions"></exception>
    public async Task CreateAsync(CreateBlogTypeDto input)
    {
        if (await _blogDbContext.BlogTypes.AnyAsync(x => x.Name == input.Name))
        {
            throw new BusinessExecptions("已经存在相同博客类型");
        }
        var data = _mapper.Map<BlogTypes>(input);
        await _blogDbContext.BlogTypes.AddAsync(data);
        await _blogDbContext.SaveChangesAsync();
    }

    public async Task DeleteAsync(Guid id)
    {
        var type = await _blogDbContext.BlogTypes.FirstOrDefaultAsync(x => x.Id == id);
        if(type != null)
        {
            _blogDbContext.BlogTypes.Remove(type);
            await _blogDbContext.SaveChangesAsync();
        }
    }
}
